package com.ftqh.tutorial

/**
 * Created by ftqh on 2017/7/14.
 */

/**
 * Note that boxing of numbers does not necessarily preserve identity
 * 注意 装箱过的数值没必要保留特征的
 */
fun doNotPreserveIdentity(){
    val a: Int = 10000
    print(a === a) // Prints 'true'
    val boxedA: Int? = a
    val anotherBoxedA: Int? = a
    print(boxedA === anotherBoxedA) // !!!Prints 'false'!!!
}
/**
 * On the other hand, it preserves equality
 * 另外一方面，它保留特性(值是相等的)
 */
fun preservesEquality(){
    val a: Int = 10000
    print(a == a) // Prints 'true'
    val boxedA: Int? = a
    val anotherBoxedA: Int? = a
    print(boxedA == anotherBoxedA) // Prints 'true'
}

fun explicitConversions(){
    // Hypothetical code, does not actually compile:
    val a: Int? = 1 // A boxed Int (java.lang.Integer)
    //val b: Long? = a // implicit conversion yields a boxed Long (java.lang.Long)
    //print(a == b) // Surprise! This prints "false" as Long's equals() check for other part to be Long as well

    val b: Byte = 1 // OK, 字面值常量会被静态检查
    //val i: Int = b // ERROR
    val i: Int = b.toInt()

    println(i)
}

fun operation(){
    val x = (1 shl 5) or 0x00000011
    println(x)
}
fun decimalDigitValue(c: Char): Int {
    if (c !in '0'..'9')
        throw IllegalArgumentException("Out of range")
    return c.toInt()-'0'.toInt() //显示转换为数值类型
}

fun arrays(){
    val array = arrayOf("1","2","3")
    for (a:String in array){
        print(a+",")
    }
    println(array.toString())
    val asc = Array(5, {i -> (i * i).toString() })
    for (a:String in asc){
        print(a+",")
    }
    println(asc)
    val x: IntArray = intArrayOf(1, 2, 3)
    x[0] = x[1] + x[2]
    for (a:Int in x){
        print(a.toString()+",")
    }
}

fun string(){
    var str:String = "Hello World"
    for (c in str) {
        println(c)
    }
    val text = """
    |for (c in "foo")
        print(c)
"""
    println(text)
    println(text.trim())
    println(text.trimMargin())
}
fun stringTemplate(){
    val i = 10
    val s = "i = $i" // evaluates to "i = 10"
    println(s)
    val s1 = "abc"
    val str = "$s1.length is ${s1.length}" // evaluates to "abc.length is 3"
    println(str)

    val price = """
    ${'$'}9.99
    """
    val price1 = """
    $9.99
    """
    println(price)
    println(price1)
}
fun main(args:Array<String>){
    doNotPreserveIdentity()
    println("------")
    preservesEquality()
    println("------")
    explicitConversions()
    println("------")
    operation()
    println("------")
    println(decimalDigitValue('9'))
    println("------")
    arrays()
    println("------")
    //string()
    println("------")
    stringTemplate()
}

